/**
*	淘宝客采集后台维护程序
*  实现单一更新和批量更新 后期会实现选择性更新
*
*/
(function(w) {
	chrome.cookies.get({url:'http://www.alimama.com',name:'_tb_token_'},function(cookie){
		tb_token = cookie.value;
		console.log(tb_token);
	});
	lunxun();
	function lunxun()
	{
		
		chrome.cookies.get({url:'http://www.alimama.com',name:'_tb_token_'},function(cookie){
				tb_token = cookie.value;
				console.log(tb_token);
				if(tb_token){
					$("#islogin").text("已登陆");		
				}
				
		});
		$.ajax('http://pub.alimama.com/index.htm').done();
		setTimeout(lunxun,1000000);
	}
	
	//按钮点击事件
	$("#searchBtn").bind('click',function(){
		getbackgrounddata(1);
	});
				
	
	
})(window);
var totalnum = 0;
var page = 0;
function getbackgrounddata(page)
{
	var gidlisturl = "http://manpianyi.cn/?r=tbk/Getgidlist&page="+page; 
		$.getJSON(gidlisturl,function(data){									
			$.each(data.gids,function(cid,v){
				$.each(v,function(k,gid){
					searchAuctionList(cid,gid);
				});
				
			});
			totalnum = data.totalnum;
	});	
}
function searchAuctionList(cid,gid)
{
	
	var timestamp = (new Date()).valueOf();
	
	var html = '';
	var tbkclickurl = '';
	
	var clickurl = 'http://pub.alimama.com/common/code/getAuctionCode.json?auctionid='+gid;
		 clickurl+='&adzoneid=14998208&siteid=4068435&t='+timestamp+'&_tb_token_='+tb_token;
	$.getJSON(clickurl,function(data){	
		tbkclickurl = data.data.clickUrl;
	});	
	timestamp = timestamp+3000;
	var url = 'http://pub.alimama.com/pubauc/searchAuctionList.json?&perPagesize=40&sort=_totalfee&toPage=1';
	url +='&t='+timestamp+'&_tb_token_='+tb_token+'&q=id%3D'+gid;
		$.getJSON(url,function(data){	
		page = page+1;	
		if(page>totalnum)
		{
			alert("已经全部完成了");
			return false;
		}
		if(!gid){
			console.log("没能获取到gid");
		}
			
		  var count = 0;		
		 if(data.data.pagelist.length==0)
		 {
		 	$.ajax({
						url:'http://manpianyi.cn/?r=tbk/delgoodsinfo',
						data:{gid:gid,cid:cid},
						datatype:"json",
						type:"POST",
						success:function(obj)
						{
							
							getbackgrounddata(page);
						}					
					})
		 }					
			$.each(data.data.pagelist,function(k,v){
				v.clickUrl = tbkclickurl;
				v.category = cid;
				var tbkjson = JSON.stringify(v);
				
				$.ajax({
						url:'http://manpianyi.cn/?r=tbk/updategoodsinfo',
						data:{tbjson:tbkjson,type:3},
						datatype:"json",
						type:"POST",
						success:function(obj)
						{
							if(obj==2)
							{
								var addnum = parseInt($("#addnum").val());
								addnum+=1;
								$("#addnum").val(addnum);
							}else if(obj==1){
								var midfilynum = parseInt($("#midfilynum").val());
									midfilynum+=1;
								$("#midfilynum").val(midfilynum);
							}else if(obj==3)
							{
								var errnum = parseInt($("#errnum").val());
								errnum+=1;
								$("#errnum").val(errnum);
							}
							getbackgrounddata(page);
						}					
					})							
				});	
		});
	
}

